package cn.threewaters.qtyy.config.shiro;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.filter.AccessControlFilter;

import cn.threewaters.qtyy.common.bean.ResponseJson;
import cn.threewaters.qtyy.dit.one.entity.SysUser;
import cn.threewaters.qtyy.util.hutool.json.JSONUtil;

public class LoginFilter extends AccessControlFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		SysUser sysUser = ShiroManager.getUserInfo();
		if (null != sysUser || isLoginRequest(request, response)) {
			return Boolean.TRUE;
		}
		if (isAjax(request)) {
			out(response, ResponseJson.builder().success(false).msg("请先进行登录认证").build());
		}
		return Boolean.FALSE;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		saveRequestAndRedirectToLogin(request, response);
		return Boolean.FALSE;
	}

	public boolean isAjax(ServletRequest request) {
		String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
		if ("XMLHttpRequest".equalsIgnoreCase(header)) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	public void out(ServletResponse response, ResponseJson responseJson) {
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");// 设置编码
			response.setContentType("application/json");// 设置返回类型
			out = response.getWriter();
			out.println(JSONUtil.toJsonStr(responseJson));// 输出
		} catch (Exception e) {
		} finally {
			if (null != out) {
				out.flush();
				out.close();
			}
		}
	}

}
